package conference.model;

import java.util.LinkedList;

import conference.TCPCommands;
import conference.model.ConferenceState;
import conference.model.ConferenceState.NOTIFICATION_TYPE;


/**
*
* A linked list containing all clients in the conference
* @author Samsjo-8
*/

public class ClientList {
	@SuppressWarnings("unused")
	private static final long serialVersionUID = 870765806071572933L;

	ConferenceState conference = null;
	private LinkedList<Client> list = new LinkedList<Client>();
	
	public ClientList(ConferenceState conferenceState){
		this.conference=conferenceState;
	}
	
	public String toTransferString(){ //TODO: finish
		String ts = "";
		for(int i = 0; i<list.size(); i++){
			ts+=list.get(i).toTransferString()+TCPCommands.separator_betweenListEntries;
		}
		return ts;
	}
	
	/**
	 * get a client by giving it's ip adress
	 * @param clientIpAddr the ip adress of the client represented as string
	 * @return the Client if exists, null if client does not exist in list
	 */
	public Client getClientFromIp(String clientIpAddr){
		
		for(int i = 0; i<this.size();i++){
			Client client = list.get(i);
			if(client.getipAddr().equals(clientIpAddr)){
				
				//System.out.println("found client with IP "+clientIpAddr+": "+client.toTransferString());
				return client;
			}
		}
		//System.out.println("No client with IP "+clientIpAddr);
		return null;
	}
	
	/**
	 * get a client from the list by giving its nickname
	 * @param nickName the nickname of the client
	 * @return the Client if exists, null if client does not exist in list
	 */
	public Client getClientFromNickname(String nickName){
		for(int i = 0; i<this.size();i++){
			Client client = list.get(i);
			if(client.getNick().equals(nickName)){
				return client;
			}
		}
		return null;
	}
	
   /**
	 * removes the given client
	 * @param o the Client to be removed from the list
   * @return true if the client was successfully removed
   */
	public boolean remove(Client o){
		if(list.remove(o)){
			
			conference.setChanged();
			conference.notifyObservers(NOTIFICATION_TYPE.CLIENT_LIST_UPDATE);
			
			return true;
		}
		return false;
	}
	
   
   /**
	 * adds the given client in the end of the list
	 * @param o the Client to be added to the list
   * @return true if the client was successfully added
   */
	public boolean add(Client c){
		if(list.add(c)){
			conference.setChanged();
			conference.notifyObservers(NOTIFICATION_TYPE.CLIENT_LIST_UPDATE);
			return true;
		}
		return false;
	}
	
   
   /**
	 * retrieves the number of clients in the list
   * @return the rumber of clients in the list
   */
	public int size(){
		return list.size();
	}
	
	
   /**
	 * get a client at a certain position
	 * @param index the index of the client
   * @return the client, or null if nonexisting.
   */
  public Client get(int index){
		return list.get(index);
	}
	
}
